// page/detail/pages/afterSale/afterSale.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    popup: false,
    reason: '注意保持商品的完好，建议您先与卖家沟通',
    reasonsId: null,
    sum: 0,
    reasons: [
      {
      id: 0,
      value: "订单不能及时送达"
    },
    {
      id: 1,
      value: "操作有误（商品、地址等选错）"
    },
    {
      id: 2,
      value: "重复下单/误下单"
    },
    {
      id: 3,
      value: "其他渠道价格更低"
    },
    {
      id: 4,
      value: "该商品降价了"
    },
    {
      id: 5,
      value: "不想买了"
    }
    ],
    showBtn: true,
    problem: '',
    addImg: [],
    addImgBtn: false,
    imgSum: 5,
    imgList: [], //上传图片列表
    imgListSum: null, //最后一次上传图片个数
    isRemoveImg: true, //是否删除过图片
    imgCenter: [] //删除过图片之后图片保存
  },
  // 问题描述
  getProblems(e) {
    const that = this;
    that.setData({
      problem: e.detail.value,
      sum: e.detail.value.length
    })
  },
  popup() {
    const that = this;
    that.setData({
      popup: true,
      description: ""
    })
  },

  closeReasons() {
    const that = this;
    that.setData({
      popup: false,
      description: "请您在此描述详细问题"
    })
  },
  changeReason(e) {
    const that = this;
    for (let i = 0; i < that.data.reasons.length; i++) {
      if (e.detail.value == that.data.reasons[i].id) {
        that.data.reasons[i].checked = true;
        that.setData({
          reason: that.data.reasons[i].value,
          reasonsId: e.detail.value
        })
        console.log(that.data.reasonsId)
      } else {
        that.data.reasons[i].checked = false
      }
    }
    that.setData({
      reasons: that.data.reasons
    })
    that.closeReasons();
  },
  radioChange(e) {
    const that = this;
    for (let i = 0; i < that.data.serveTypes.length; i++) {
      if (e.detail.value == that.data.serveTypes[i].id) {
        that.data.serveTypes[i].checked = true
      } else {
        that.data.serveTypes[i].checked = false
      }
    }
    if (e.detail.value == 1) {
      that.setData({
        serveTypes: that.data.serveTypes,
        type: e.detail.value,
        isReceived: 1,
        receive: 1
      })
    } else {
      that.setData({
        serveTypes: that.data.serveTypes,
        type: e.detail.value,
        isReceived: 0,
        receive: 0
      })
    }
  },
  // 添加图片
  addImg() {
    const that = this;
    console.log(that.data.showBtn)
    var imgSum = that.data.imgSum;
    wx.chooseImage({
      count: imgSum,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        let imgUrl = [];
        that.data.addImg.forEach((data) => {
          imgUrl.push(data)
        })
        tempFilePaths.forEach((data) => {
          imgUrl.push(data)
        })
        imgSum -= tempFilePaths.length;
        if (imgSum <= 0) {
          that.setData({
            addImgBtn: true
          })
        }
        that.setData({
          addImg: imgUrl,
          imgSum: imgSum,
          showBtn: false
        })
        var pics = that.data.addImg;
        that.uploadimg({
          url: app.api.reqUrls.uploadFile, //这里是你图片上传的接口
          path: pics //这里是选取的图片的地址数组
        });

      }
    })
  },
  // 删除图片
  removeImg(e) {
    const that = this;
    var imgSum = that.data.imgSum;
    const imgListLength = that.data.imgList.length;

    let imgStart = imgListLength - (that.data.imgListSum + 1);
    if (!that.data.isRemoveImg) {
      imgStart = 0;
    }
    let imgCenter = that.data.imgList.slice(imgStart, imgListLength);
    wx.showModal({
      title: '提示',
      content: '是否删除',
      success(res) {
        if (res.confirm) {
          imgSum++;
          let imgUrl = that.data.addImg;
          let sum = e.currentTarget.dataset.index;
          console.log(sum)
          imgCenter.splice(sum, 1)
          imgUrl.splice(sum, 1);
          that.setData({
            addImg: imgUrl,
            addImgBtn: false,
            imgList: imgCenter,
            imgCenter: imgCenter,
            isRemoveImg: false,
            imgSum
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }

      }
    })
  },
  //多张图片上传
  uploadimg(data) {
    var that = this,
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    let imgList = that.data.imgList;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'comment_img_file', //这里根据自己的实际情况改
      formData: null, //这里是上传图片时一起上传的数据
      success: (resp) => {
        success++; //图片上传成功，图片上传成功的变量+1
        that.setData({
          imgListSum: i
        })
        let res = JSON.parse(resp.data)
        if (res.status == 1) {
          imgList.push(res.result)
          that.setData({
            imgList: imgList,
            isRemoveImg: true
          })
        } else {
          console.log(res.msg)
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
      },
      fail: (res) => {
        wx.showToast({
          title: '图片上传失败',
          icon: 'none',
          duration: 2000
        })
        fail++; //图片上传失败，图片上传失败的变量+1
        console.log('fail:' + i + "fail:" + fail);
        that.setData({
          showBtn: true
        })
      },
      complete: () => {
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用          
          console.log('执行完毕');

          console.log('成功：' + success + " 失败：" + fail);
          that.setData({
            showBtn: true
          })
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    })
  },
  // 点击提交
  addAfterSale() {
    const that = this;
    console.log(that.data.imgList)
    if (that.data.isRemoveImg) {
      var imgSum = that.data.imgSum;
      const imgListLength = that.data.imgList.length;
      const imgStart = imgListLength - (that.data.imgListSum + 1);
      let imgCenter = that.data.imgList.slice(imgStart, imgListLength);
      const token = app.globalData.token;
      that.upFile(imgCenter);
    } else {
      let imgCenter = that.data.imgCenter;
      that.upFile(imgCenter);
    }
  },
  upFile(imgCenter) {
    const that = this;
    if (that.data.reasonsId == null) {
      wx.showModal({
        content: '请选择提交原因',
        showCancel: false,
        confirmText: '我知道了',
        confirmColor: '#ff5151',
        success(e) {

        }
      })
    } else if (that.data.problem == '') {
      wx.showModal({
        content: '请填写问题描述',
        showCancel: false,
        confirmText: '我知道了',
        confirmColor: '#ff5151',
        success(e) {

        }
      })                                                           
    } else if (that.data.imgList == '') {
      wx.showModal({
        content: '请上传问题图片资料',
        showCancel: false,
        confirmText: '我知道了',
        confirmColor: '#ff5151',
        success(e) {
        }
      })
    } else {
      let json = {
        token: app.globalData.token,
        order_id: that.data.orderid,
        reason: that.data.reason,
        describe: that.data.problem,
        imgs: imgCenter
      }
      console.log(json)
      // return false
      that.setData({
        hiddenLoading: false
      })
      let jsonData = app.utils.getSignData(json);
      app.utils.post(app.api.reqUrls.addReturnOrder, jsonData).then(res => {
        that.setData({
          hiddenLoading: true
        })
        if (res.status == 1) {
          console.log(res)
          wx.showToast({
            title: res.msg,
            icon: 'success',
            duration: 2000,
            success: (() => {
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                  success() {
                    that.data.prevPage.getOrderList();
                    setTimeout(() => {
                      wx.navigateTo({
                        url: '/page/detail/pages/returns/returns'
                      })
                    }, 600)
                  },
                  fail(err) {
                    console.log(err)
                  }
                })
              }, 2000)
            })
          })

        } else {
          throw res.msg
        }
      }).catch(err => {
        that.setData({
          hiddenLoading: true
        })
        app.showInfo(err.toString())
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    that.setData({
      orderid: options.orderid,
      hiddenLoading: true
    })
    console.log(options)
    let pages = getCurrentPages();
    let currPage = null; //当前页面
    let prevPage = null; //上一个页面
    if (pages.length >= 2) {
      currPage = pages[pages.length - 1]; //当前页面
      prevPage = pages[pages.length - 2]; //上一个页面
    }
    that.setData({
      order_id: options.orderid,
      order_sn: options.order_sn,
      currPage,
      prevPage
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },
})